/*
 * $(document).ready(function() { alert("document ready occurred!"); });
 * 
 * $(window).load(function() { alert("window load occurred!"); });
 */

var mapCli = {};
mapCli.map = null;
mapCli.marker = null;
mapCli.geocoder = null;
mapCli.infowindow = new google.maps.InfoWindow();
mapCli.results = {};
mapCli.isExibirInfoWindow = false;
mapCli.zoom = 15;

function initialize() {

	mapCli.geocoder = new google.maps.Geocoder();

	// Try W3C Geolocation (Preferred)
	if (navigator.geolocation) {
		mapCli.browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(showMapW3, locationError, {
			enableHighAccuracy : true
		});

		// Try Google Gears Geolocation
	} else if (google.gears) {
		mapCli.browserSupportFlag = true;
		var geo = google.gears.factory.create('beta.geolocation');
		geo.getCurrentPosition(showMapW3, locationError, {
			enableHighAccuracy : true
		});

		// Browser doesn't support Geolocation
	} else {
		mapCli.browserSupportFlag = false;
		handleNoGeolocation(browserSupportFlag);
	}
}

function showMapW3(position) {

	mapCli.map = new google.maps.Map(document.getElementById('gmap'), {
		center : new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
		zoom : mapCli.zoom,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	});

	mapCli.marker = new google.maps.Marker({
		map : mapCli.map,
		position : mapCli.map.getCenter(),
		draggable : true
	});

	google.maps.event.addListener(mapCli.marker, 'dragend', function(event) {
		mapCli.map.setCenter(event.latLng);
		codeLatLng();
	});

	google.maps.event.addListener(mapCli.map, 'dblclick', function(event) {
		mapCli.map.setCenter(event.latLng);
		codeLatLng();
	});

	codeLatLng();
}

function showMap(center) {

	mapCli.map = new google.maps.Map(document.getElementById('gmap'), {
		center : new google.maps.LatLng(center.lat(), center.lng()),
		zoom : mapCli.zoom,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	});

	mapCli.marker = new google.maps.Marker({
		map : mapCli.map,
		position : mapCli.map.getCenter(),
		draggable : true
	});

	google.maps.event.addListener(mapCli.marker, 'dragend', function(event) {
		mapCli.map.setCenter(event.latLng);
		codeLatLng();
	});

	google.maps.event.addListener(mapCli.map, 'dblclick', function(event) {
		mapCli.map.setCenter(event.latLng);
		codeLatLng();
	});

	codeLatLng();
}

function locationError(error) {
	switch (error.code) {
	case 0: // UNKNOWN_ERROR
		alert('An unknown error occurred');
		break;
	case 1: // PERMISSION_DENIED
		alert('Permission to use Geolocation API denied');
		break;
	case 2: // POSITION_UNAVAILABLE
		alert('Could not determine location');
		break;
	case 3: // TIMEOUT
		alert('The geolocation request timed out');
		break;
	default:
	}
}

function codeAddress() {
	var address = "";
	if (document.getElementById("form_endereco:logradouro").value == "") {
		if (document.getElementById("form_endereco:cep").value == "") {
			alert('Informe CEP ou LOGRADOURO');
		} else {
			address += document.getElementById("form_endereco:cep").value;
		}
	} else {
		address += document.getElementById("form_endereco:logradouro").value;
		if (document.getElementById("form_endereco:numero").value !== "") {
			address += "," + document.getElementById("form_endereco:numero").value;
		}
		if (document.getElementById("form_endereco:bairro").value !== "") {
			address += "," + document.getElementById("form_endereco:bairro").value;
		}
		if (document.getElementById("form_endereco:localidade").value !== "") {
			address += "," + document.getElementById("form_endereco:localidade").value;
		}
		if (document.getElementById("form_endereco:uf").value !== "") {
			address += "," + document.getElementById("form_endereco:uf").value;
		}
		if (document.getElementById("form_endereco:pais").value !== "") {
			address += "," + document.getElementById("form_endereco:pais").value;
		}
	}

	if (mapCli.geocoder) {
		mapCli.geocoder.geocode({
			'address' : address
		}, codeFunction);
	}
}

function codeLatLng() {
	if (mapCli.geocoder) {
		mapCli.geocoder.geocode({
			'latLng' : mapCli.map.center
		}, codeFunction);
	}
}

function codeFunction(results, status) {
	if (status == google.maps.GeocoderStatus.OK) {
		if (results[0]) {
			mapCli.results = results[0];
			mapCli.map.setZoom(mapCli.zoom);
			mapCli.map.setCenter(mapCli.results.geometry.location);
			mapCli.marker.setPosition(mapCli.map.center);
			if (mapCli.isExibirInfoWindow) {
				mapCli.infowindow.setContent(results[0].formatted_address);
				mapCli.infowindow.open(mapCli.map, mapCli.marker);
			}
			loadAddress();
		}
	} else {
		alert("Endereço não encontrado. Geocoder falhou - Status: " + status);
	}
}

function loadAddress() {

	var i = 0;
	var temp = "";

	temp = document.getElementById("enderecoCompleto");
	temp.textContent = mapCli.results.formatted_address;

	temp = document.getElementById("form_endereco:latLng");
	temp.value = mapCli.results.geometry.location.lat() + "," + mapCli.results.geometry.location.lng();

	for (i = 0; i < mapCli.results.address_components.length; i++) {
		if (mapCli.results.address_components[i].types[0] === 'street_number') { // numero
			temp = document.getElementById("form_endereco:numero");
			temp.value = mapCli.results.address_components[i].long_name;
		} else if (mapCli.results.address_components[i].types[0] === 'route') { // logradouro
			temp = document.getElementById("form_endereco:logradouro");
			temp.value = mapCli.results.address_components[i].long_name;
		} else if (mapCli.results.address_components[i].types[0] === 'sublocality') { // bairro
			temp = document.getElementById("form_endereco:bairro");
			temp.value = mapCli.results.address_components[i].long_name;
		} else if (mapCli.results.address_components[i].types[0] === 'locality') { // cidade
			temp = document.getElementById("form_endereco:localidade");
			temp.value = mapCli.results.address_components[i].long_name;
		} else if (mapCli.results.address_components[i].types[0] === 'administrative_area_level_1') { // Estado
			temp = document.getElementById("form_endereco:uf");
			temp.value = mapCli.results.address_components[i].short_name;
		} else if (mapCli.results.address_components[i].types[0] === 'country') { // País
			temp = document.getElementById("form_endereco:pais");
			temp.value = mapCli.results.address_components[i].short_name;
		} else if (mapCli.results.address_components[i].types[0] === 'postal_code') { // CEP
			temp = document.getElementById("form_endereco:cep");
			temp.value = mapCli.results.address_components[i].long_name;
		}
	}
}

function detectBrowser() {
	var useragent = navigator.userAgent;
	var mapdiv = document.getElementById("gmap");

	if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1) {
		mapdiv.style.width = '100%';
		mapdiv.style.height = '100%';
	} else {
		mapdiv.style.width = '600px';
		mapdiv.style.height = '800px';
	}
}
